//
//  RemarkTable.m
//  CWeekly
//
//  Created by  on 12-4-23.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "RemarkTable.h"
#import <QuartzCore/QuartzCore.h>
#import "DataProvider.h"
#import "UserCenter.h"
#import "ASIHTTPRequest.h"
#import "JSON.h"
@implementation RemarkTable
@synthesize tv,markArray;
-(void)dealloc{
    [markArray release];
    [tv release];
    [super dealloc];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code

        table=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, 740, frame.size.height) style:UITableViewStylePlain];
        table.showsVerticalScrollIndicator=NO;
        table.delegate=self;
        table.dataSource=self;
        table.backgroundColor=[UIColor clearColor];
        table.separatorStyle=UITableViewCellSelectionStyleNone;
        [self addSubview:table];
        [table release];
        
//        UIImageView* leftmark=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"textfiled2.png"]];
//        leftmark.frame=CGRectMake(20, 5, 690, 25);
        UIView*view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 740, 30)];
        view.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"advs_cell_bg.png"]];
//        [view addSubview:leftmark];
//        [leftmark release];
//        table.tableHeaderView=view;
//        [view release];
        
        
        textFieldView=[[UIView alloc] init];
        textFieldView.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"advs_bg.png"]];
        tv=[[UITextView alloc] initWithFrame:CGRectMake(20, 0, 225, frame.size.height-30)];
        tv.backgroundColor=[UIColor clearColor];
        UITextField *imgView = [[UITextField alloc]initWithFrame: CGRectMake(20, 35, 225, frame.size.height-30)];
        imgView.tag=999;
        imgView.borderStyle=UITextBorderStyleRoundedRect;

        [textFieldView addSubview: imgView];
        [textFieldView sendSubviewToBack:imgView];
        [imgView release];

        tv.textColor=[UIColor blackColor];
        tv.font=[UIFont systemFontOfSize:18];
        [[tv layer] setMasksToBounds:YES];
        tv.delegate=self;
        [textFieldView addSubview:tv];
        [tv becomeFirstResponder];
        [self addSubview:textFieldView];
        [textFieldView release];
        
        UIButton* but=[UIButton buttonWithType:UIButtonTypeCustom];
        but.tag=888;
        [but addTarget:self action:@selector(dismissView) forControlEvents:UIControlEventTouchUpInside];
        [but setImage:[UIImage imageNamed:@"advs_send_btn.png"] forState:UIControlStateNormal];
        [textFieldView addSubview:but];
        markArray=[[NSMutableArray alloc] init];
    }
    return self;
}


- (void)loadData
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
    
    DataProvider *dp = [DataProvider sharedManager];
    DPData *dpData = [dp getMarkList];
    
    if (dpData.isSuccess) {
        if ([[dpData.data objectForKey:@"json"] count]>0) {
            [markArray removeAllObjects];
            [markArray addObjectsFromArray:[dpData.data objectForKey:@"json"]];
            [[NSUserDefaults standardUserDefaults] setValue:markArray forKey:@"BOOKS"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
        else {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle: nil 
                                                           message: @"获取评论失败"
                                                          delegate: self 
                                                 cancelButtonTitle: @"确定" 
                                                 otherButtonTitles: nil];
            [alert show];
            [alert release];
        }
        [self performSelectorOnMainThread:@selector(loadEnd) withObject:nil waitUntilDone:NO];
        
    }
    else {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle: nil 
                                                       message: dpData.data
                                                      delegate: self 
											 cancelButtonTitle: @"确定" 
                                             otherButtonTitles: nil];
		[alert show];
		[alert release];
    }
    [pool release];
    
}

- (void)loadEnd
{
    [table reloadData];
}
-(void)sendmark:(NSString*)str{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
    NSString* urlstr=[[SERVER stringByAppendingFormat:@"SynMgController?cmd=1008&"] stringByAppendingString:str];
    NSLog(@"＋＋＋%@",urlstr);
    urlstr= [urlstr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    ASIHTTPRequest*req=[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:urlstr]];
    [req setRequestMethod:@"GET"];
    //    NSMutableData* bodyData=[NSMutableData dataWithData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //    [req setPostBody:bodyData];
    [req startSynchronous];
    NSData*resPonse=[req responseData];
    NSString*sstr=[[NSString alloc] initWithData:resPonse encoding:NSUTF8StringEncoding];
    sstr = [sstr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"ivoke-------   %@",sstr);
    NSDictionary* result=[sstr JSONValue];
    if ([[result valueForKey:@"status"] intValue]==1) {
        //        同步成功
        [tv performSelectorOnMainThread:@selector(setText:) withObject:@"" waitUntilDone:[NSThread isMainThread]];
        [self loadData];
        return;
    }else {
        UIAlertView* al=[[[UIAlertView alloc] initWithTitle:@"提示" message:[result valueForKey:@"message"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil] autorelease];
        [al show];
    }

    [pool release];
}
-(void)dismissView{
    NSDate*date=[NSDate date];
    NSTimeZone* timezone=[NSTimeZone localTimeZone];
    NSDateFormatter*format=[[NSDateFormatter alloc] init];
    [format setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    [format setTimeZone:timezone];
    NSString* time=[format stringFromDate:date];

    NSString* uid=[[UserCenter defaultUser].userId stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString* uname=[[UserCenter defaultUser].username stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString* tit=[[NSString stringWithString:@"标题党"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSString* String=[NSString stringWithFormat:@"param={\"CContent\":\"%@\",\"CTime\":\"%@\",\"CTitle\":\"%@\",\"CUserid\":\"%@\",\"CUsername\":\"%@\"}",[tv.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],time,tit,uid,uname];

    [NSThread detachNewThreadSelector:@selector(sendmark:) toTarget:self withObject:String];
    [tv resignFirstResponder];
}
-(void)reFreshFrame:(CGRect)frame{
    NSLog(@"hhhhhh=%f,wwwwww==%f",frame.size.height,frame.size.width);
    self.frame=frame;
    UITextField* v=(UITextField*)[textFieldView viewWithTag:999];
    UIButton* b=(UIButton*)[textFieldView viewWithTag:888];
    if (frame.size.width>800){
        CGFloat h=frame.size.height*2/3;
        table.frame=CGRectMake(0, 0, 740, h);
        textFieldView.frame=CGRectMake(self.frame.size.width-275, 0, 275,h);
        tv.frame=CGRectMake(20, 10, 225, h-30-30);
        v.frame=CGRectMake(20, 10, 225, h-30-30);
        b.frame=CGRectMake(200, h-30, 50, 26);
    }else {
        table.frame=CGRectMake(0, 0, frame.size.width, frame.size.height*3/4);
        textFieldView.frame=CGRectMake(0, frame.size.height*3/4+30, frame.size.width,frame.size.height/4-30);
        tv.frame=CGRectMake(20, 5, frame.size.width-40,frame.size.height/4-30-50);
        v.frame=CGRectMake(20, 5, frame.size.width-40, frame.size.height/4-30-50);
        b.frame=CGRectMake(frame.size.width-80, frame.size.height/4-60, 50, 26);
    }
}



-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  markArray.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString* iden=@"cell";

    UITableViewCell* cell=[table dequeueReusableCellWithIdentifier:iden];
    if (cell==nil) {
        cell=[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:iden] autorelease];
    }
    NSDictionary* dic=[markArray objectAtIndex:indexPath.row];
    cell.backgroundView=[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"advs_cell_bg.png"]] autorelease];
    cell.imageView.image=[UIImage imageNamed:@"headerIcon.png"];
    cell.textLabel.text=[dic valueForKey:@"CTitle"];
    cell.detailTextLabel.text=[NSString stringWithFormat:@"%@  %@",[dic valueForKey:@"CContent"],[dic valueForKey:@"CTime"]];
    cell.textLabel.textColor=[UIColor whiteColor];
    return cell;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
